import Cesium from '../Ces/Cesium'

/**
 * base class
 */
class WeCustomTextureUniform {
  name: string
  texture: any
  rectangle: any
  constructor(options) {
    this.name = options.name
  }

  setImage(image, context) {
    const { west, south, east, north, source } = image
    if (source) {
      this.texture = new Cesium.Texture({
        context,
        pixelFormat: source.pixelFormat,
        pixelDatatype: source.pixelDatatype || source.pixelType,
        source,
      })
    } else {
      this.texture = new Cesium.Texture({
        context,
        source: image,
      })
    }

    if (west && south && east && north) {
      this.rectangle = Cesium.Rectangle.fromDegrees(west, south, east, north)
    }
  }

  getSource() {
    const samplerUniform = this.texture._depth > 1 ? 'sampler3D' : 'sampler2D';

    const rectangle = this.rectangle
    const extent = rectangle ? `
        vec4 weget_extent${this.name}(){
            return vec4(${rectangle.west},${rectangle.south},${rectangle.east},${rectangle.north});
        }
        ` :
      `
         vec4 weget_extent${this.name}(){
            return vec4(0.0);
        }
        `
    const source = `
        #define HasCustomTexture0
        precision highp ${samplerUniform};\n
        uniform ${samplerUniform} u_${this.name};\n
        ${extent}
        `;

    return source
  }

  setupUniformMap(uniformMap) {
    const { name } = this
    uniformMap[`u_${name}`] = () => this.texture
  }

  destroy() {
    this.texture = this.texture && this.texture.destroy()
    return Cesium.destroyObject(this)
  }

  isDestroyed() {
    return false
  }
}

export default WeCustomTextureUniform
